package com.chanyachting.emall.util;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;

import com.jspsmart.upload.Request;
import com.jspsmart.upload.SmartUpload;

/**
 * 处理带有文件上传的表单提交。
 * 在action中使用。
 * 不能与actionform 同时使用
 * @author robert
 *
 */
public class SmartUploadUtil {
	
	private SmartUpload mySmartUpload;
	
	private Request request;
	
	private HttpServletRequest serRequest;
	
	public SmartUploadUtil(Action action,HttpServletRequest request, HttpServletResponse response){
		
		this.mySmartUpload=new com.jspsmart.upload.SmartUpload();
		
		this.serRequest=request;
		
		 //初始化
	   try {
		//this.mySmartUpload.initialize(action.getServlet().getServletConfig(), request, response);
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} 
		
		this.request=this.mySmartUpload.getRequest();
		
	}
	
	public String getParameter(String args){
		
		return this.request.getParameter(args);
	}
	
	
	public String getParameter(String args,String def){
		
		return this.getParameter(args)==null?def:this.getParameter(args);
	}
	
	
	/**
	 * 处理文件上传表单， 返回文件上传后的web访问路径  
	 * 
	 * @return "http://localhost:8080/xxxx/userfile/xxx.img"
	 */
	public String processImgUpload(){
		
		String returnUrl="";
		
		RequestUtil ru=new RequestUtil(this.serRequest);
		
		try {

		    //设置上载的最大值
		    mySmartUpload.setMaxFileSize(500 * 1024*1024);
		    //上载文件
		    mySmartUpload.upload();
		    
		    for (int i=0;i<mySmartUpload.getFiles().getCount();i++){
		    	
		    	com.jspsmart.upload.File myFile = mySmartUpload.getFiles().getFile(i);
		    	
		    	if(myFile.isMissing()) continue;   //如果文件丢失，跳入下一个循环

		      	String imgUrl=ru.getImgUploadPath()+myFile.getFileName();
		      	  
		      	myFile.saveAs(imgUrl,mySmartUpload.SAVE_PHYSICAL);  //保存文件到服务器
		      	
		      	//获得文件web访问路径
		      	returnUrl=ru.getImgWebUrl(myFile.getFieldName());

		    }
			
		} catch (Exception e) {
			
			e.printStackTrace();
		}

		return returnUrl;
	}

}
